<?php

namespace lib\Oss;

class OssUpload
{

    /**
     * oss上传文件
     * @param $name
     * @return array
     * @throws \OSS\Core\OssException
     */
    public static function uploadFile($fileName,$tmpFile,$fileSize)
    {

        $ossClient  = AliOss::getOssClient();
        $bucketName = AliOss::getBucketName();
        /*// 文件名
        $fileName = $_FILES[$name]['name'];
        // 临时文件位置
        $tmpFile = $_FILES[$name]['tmp_name'];
        $fileSize = $_FILES[$name]['size'];*/
        if (round($fileSize / 1048576 * 100) / 100 > 20){
            return [
                'errorCode' => 2,
                'msg' => '文件大小不能超过20M'
            ];
        }

        //限制文件类型
        $allowExtensions = array('jpg', 'jpeg', 'png', 'bmp', 'wbmp', 'gif', 'icon', 'doc','rar','zip','mp4','pdf');
        $extension = self::getExtension($fileName);
        if (!in_array($extension,$allowExtensions)){
            $data = [
                'errorCode' => 1,
                'msg' => '抱歉，不支持此类型的文件上传'
            ];
            return $data;
        }

        // 定义文件存储的oss位置
        $ossPath = 'file/'.md5(date('YmdHis').mt_rand(10000,99999)).'/'.date('His') .mt_rand(10000,99999);
        $localPath = public_path().'/upload/'.$ossPath.'.' . $extension;
        $object = $ossPath .'.' . $extension;

        //判断如果是图片进行等质压缩
        $imageExtensions = array('jpg', 'jpeg', 'png', 'bmp', 'wbmp', 'gif');
        // 定义oss object
        $isImage = in_array($extension,$imageExtensions);

        if ($isImage){
            //图片等质量压缩
            $img  = new ImgCompress($tmpFile,1);
            $img->compressImg($localPath);
            // 执行上传并获取返回 oss 信息
            $info = $ossClient->uploadFile($bucketName, $object, $localPath);
        }else{
            // 执行上传并获取返回 oss 信息
            $info = $ossClient->uploadFile($bucketName, $object, $tmpFile);
        }

        $ossUrl = $info['oss-request-url'];
        //把oss域名换成CDN加速域名
        $ossUrlArr = parse_url($ossUrl);
        $ossUrl = getenv('OSS_HTTP_PROTOCOL').'://'
            .getenv('OSS_CDNDOMAIN')
            .$ossUrlArr['path'];

        $data = ['errCode' => 0,
            'msg' => '上传成功',
            'data'=>[
                'file_url'  => $ossUrl,
                'file_name' => basename($ossUrl)
            ]
        ];


        return $data;
    }


    /**
     * 返回文件扩展名
     *
     * @param $fileName
     * @return mixed
     */
    public static function getExtension($fileName)
    {
        return pathinfo($fileName)['extension'];
    }

}